package com.system.core.security.impl;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

import com.system.core.security.NameUtil;
import com.system.core.security.SignBuilder;
import com.system.core.security.SignUtil.SignParam;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class WechatHMACSHA256Builder implements SignBuilder {
	
	private String key;

	@Override
	public String buildSign(String source) {
		try {
			Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
			sha256_HMAC.init(secret_key);
			return Hex.encodeHexString(sha256_HMAC.doFinal(source.getBytes("utf-8")), false);
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}

	@Override
	public String buildSignSrouce(SignParam signParam) {
		StringBuffer stringBuffer = new StringBuffer();
		signParam.getDataMap().forEach((key,value)->{
			stringBuffer.append("&"+NameUtil.javaName2_(key)+"="+value);
		});
		stringBuffer.append("&key="+key);
		stringBuffer.delete(0, 1);
		return stringBuffer.toString();
	}

}
